package it.koutifaris.travianmap.dal.sqlservices.tile;

import static it.koutifaris.travianmap.context.ContextRetreiver.contextRetreiver;
import it.koutifaris.travianmap.context.HasApplicationContex;
import it.koutifaris.travianmap.model.Village;
import it.koutifaris.travianmap.model.impl.VillagesLoader;

import java.util.List;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Parcel;
import android.os.Parcelable;

class VillagesLoaderImpl extends HasApplicationContex implements VillagesLoader {

	private final int playerId;
	private final long revisionId;

	public VillagesLoaderImpl(int playerId, long revisionId) {
		this.playerId = playerId;
		this.revisionId = revisionId;
	}

	@Override
	public List<Village> getVillages() {
		Cursor cursor = getDatabase().rawQuery(getQuery(), getSelectionArgs());
		List<Village> result = new MapDataExtractor().getVillagesFromCursor(cursor);

		return result;
	}

	public SQLiteDatabase getDatabase() {
		return contextRetreiver().getCurrentContext().getCurrentSqlMapDbHelper().getReadableDatabase();
	}

	private String getQuery() {
		return VillagesOfPlayerQuery.getVillagesInBoundQuery();
	}

	private String[] getSelectionArgs() {
		return VillagesOfPlayerQuery.getSelectionArgs(revisionId, playerId);
	}

	@Override
	public int describeContents() {
		return 0;
	}

	@Override
	public void writeToParcel(Parcel dest, int flags) {
		dest.writeInt(playerId);
		dest.writeLong(revisionId);
	}

	public final static Parcelable.Creator<VillagesLoaderImpl> CREATOR = new Parcelable.Creator<VillagesLoaderImpl>() {

		@Override
		public VillagesLoaderImpl createFromParcel(Parcel source) {
			int playerId = source.readInt();
			long revisionId = source.readLong();

			return new VillagesLoaderImpl(playerId, revisionId);
		}

		@Override
		public VillagesLoaderImpl[] newArray(int size) {
			return new VillagesLoaderImpl[size];
		}
	};

}
